var createError = require("http-errors");
var express = require("express");
const bodyParser = require("body-parser");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

const cors = require("cors");
var indexRouter = require("./routes/index");
var usersRouter = require("./routes/admin/user");
const { verify } = require("./util/jwt");
var app = express();
app.use(cors()); // 使用默认配置允许所有来源的跨域请求
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// 静态资源
app.use(express.static(path.join(__dirname, "public")));
// post请求
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use("/", indexRouter);
app.use((req, res, next) => {
  // 如果token 有效 next
  // 如果token无效 返回401错误
  console.log(req.url);
  if (req.url === "/api/users/login") {
    next();
  } else {
    const token = req.headers["authorization"];
    if (token) {
      if (verify(token)) {
        next();
      } else {
        res.send({
          code: 401,
          message: "token失效",
        });
      }
    }
  }
});
app.use("/api", usersRouter);

module.exports = app;
